<?php

/**
 * @Description    组织架构, 部门
 * @Author         zhaojiping
 * @Copyright      Copyright (c) 山东艾思软件科技有限公司(https://www.aisisofit.cn)
 * @Date           2022/2/7
 * @CreateBy       VS Code
 */

namespace app\core\model;

use think\Model;
use think\facade\Db;


class CoreDepartment extends \app\common\model\CommonModel {

    protected $fields = 'id, pid, name, sort, is_system, is_shop'; // 通用查询字段
    protected $order = 'sort, id'; // 排序字段

    public static function onBeforeInsert($row) {
        parent::onAfterInsert($row);

        if ($row['pid'] <= 0) json_return(0, '请选择上级部门');

        cache('core_department_all', null);
    }

    public static function onAfterRead($row) {
        parent::onAfterRead($row);

        if (isset($row['is_system'])) $row['show_delete'] = $row['is_system'] ? 0 : 1;
    }

    public static function onBeforeUpdate($row) {
        // p($row);
        if ($row['is_shop'] == 1) {
            $count = self::where('pid', '=', $row['id'])->count();
            // echo self::getlastsql();
            if ($count > 0)
                json_return(0, '门店下面不能有下级组织, 此组织不能修改为门店');
        }

        parent::onBeforeUpdate($row);

        if ($row['id'] == $row['pid'])
            json_return(0, '组织架构的父类不能是本身, 请重新选择');

        cache('core_department_all', null);
    }

    public static function onBeforeDelete($row) {
        parent::onBeforeDelete($row);

        if ($row['is_system'] === 1) json_return(0, '系统基础配置不可删除！');

        $result = self::where('pid', 'in', $row['id'])->count();
        if ($result > 0)
            json_return(0, '当父组织架构下面有子组织架构, 父组织架构不能删除, 请先删除子组织架构');

        $result = Db::name('CoreUser')->where(['department_id' => $row['department_id']])->count();
        if ($result > 0)
            json_return(0, '有员工属于该部门, 请先删除或修改属于该部门的员工');


        cache('core_department_all', null);
    }

    /**
     * 查询department的所有父级部门
     * @param int $department_id: 要查询的部门
     * @return array 返回所有父级部门的ID
     */
    public static function getParentDepartmentIds($department_id) {
        static $arr; // 定义一个静态变量, 存储嵌套时的变量
        $arr[] = $department_id;
        $pid = Db::name('CoreDepartment')->cache(3)->where('id', '=', $department_id)->value('pid');
        if ($pid > 0) {
            self::getParentDepartmentIds($pid);
        }
        return $arr;
    }
}
